package org.xtown.bingluo.xtieba.ui.activities;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.xtown.bingluo.xtieba.R;
import org.xtown.bingluo.xtieba.db.XtiebaAuthorDb;
import org.xtown.bingluo.xtieba.db.XtiebaPostsDb;
import org.xtown.bingluo.xtieba.db.XtiebaPostsInfoDb;
import org.xtown.bingluo.xtieba.model.XtiebaAuthor;
import org.xtown.bingluo.xtieba.model.XtiebaPosts;
import org.xtown.bingluo.xtieba.sync.CrawlSyncTask;
import org.xtown.bingluo.xtieba.sync.ISyncListener;
import org.xtown.bingluo.xtieba.sync.SyncTaskInfo;
import org.xtown.bingluo.xtieba.sync.ToTiebaQueryParameter;
import org.xtown.bingluo.xtieba.ui.components.MarqueeText;
import org.xtown.bingluo.xtieba.utils.ApplicationUtils;
import org.xtown.bingluo.xtieba.utils.DateUtils;
import org.xtown.bingluo.xtieba.utils.IOUtils;
import org.xtown.bingluo.xtieba.utils.LogUtlils;
import org.xtown.bingluo.xtieba.utils.NetUtils;
import org.xtown.bingluo.xtieba.utils.UiUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CrawlActivity extends BaseActivity implements ISyncListener {

	public static CrawlActivity INSTANCE = null;

	public static final int POSTS_INFO_ACTIVITY_REQUESTCODE = 102;

	private Button DoCrawlBtn;

	protected SyncTaskInfo mSyncTaskInfo;
	protected CrawlSyncTask mSyncTask;
	private static final AtomicReference<AsyncTask<SyncTaskInfo, Integer, Throwable>> mSyncThread = new AtomicReference<AsyncTask<SyncTaskInfo, Integer, Throwable>>();

	protected ProgressDialog mProgressDialog;

	private EditText CrawlMandate;

	private String currentKzid = "";

	private XtiebaPosts currentXtiebaPostsDb;

	private int currentPosts_id;

	private ImageView CurrentPosts_Thumbnail;

	private TextView CurrentPosts_Author;

	private MarqueeText CurrentPosts_Title;

	private TextView CurrentPosts_KZID;

	private MarqueeText CurrentPosts_Total;

	private TextView CurrentPosts_Date;

	private TextView CurrentPosts_UpdateDate;

	private int postsCount;

	private LinearLayout CurrentPostsView;

	private Button DoAdditionalCrawlBtn;

	private Button DoNormalCrawlBtn;

	protected ToTiebaQueryParameter ToTiebaQueryParameterData;

	private enum SwitchUpdateUiCommand {
		INIT, UpdateCurrentPostsViewData
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		INSTANCE = this;
		setContentView(R.layout.crawl_activity);
		processExtraData();
		initData();
		buildComponents();
		updateUI(SwitchUpdateUiCommand.INIT);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		setIntent(intent);// must store the new intent unless getIntent() will
							// return the old one
		LogUtlils.println("---------onNewIntent");
		processExtraData();
	}

	private void processExtraData() {
		Intent intent = getIntent();
		if (intent.hasExtra(XtiebaPostsDb.KZID)) {
			currentKzid = intent.getStringExtra(XtiebaPostsDb.KZID);
		}
		LogUtlils.println("---------currentKzid=" + currentKzid);
	}

	private void initData() {
		initCurrentPostsViewData(currentKzid);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {

		case POSTS_INFO_ACTIVITY_REQUESTCODE:
			break;
		default:
			break;
		}
	}

	/**
	 * Create main UI.
	 */
	private void buildComponents() {

		CurrentPostsView = (LinearLayout) findViewById(R.id.CurrentPostsView);
		CurrentPosts_Thumbnail = (ImageView) findViewById(R.id.CurrentPosts_Thumbnail);
		CurrentPosts_Author = (TextView) findViewById(R.id.CurrentPosts_Author);
		CurrentPosts_Title = (MarqueeText) findViewById(R.id.CurrentPosts_Title);
		CurrentPosts_KZID = (TextView) findViewById(R.id.CurrentPosts_KZID);
		CurrentPosts_Total = (MarqueeText) findViewById(R.id.CurrentPosts_Total);
		CurrentPosts_Date = (TextView) findViewById(R.id.CurrentPosts_Date);
		CurrentPosts_UpdateDate = (TextView) findViewById(R.id.CurrentPosts_UpdateDate);

		CurrentPostsView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent i = new Intent();
				i.setClass(INSTANCE, PostsInfoActivity.class);
				i.putExtra(XtiebaPostsDb.KZID, currentKzid);
				if (i != null) {
					INSTANCE.startActivityForResult(i,
							POSTS_INFO_ACTIVITY_REQUESTCODE);
				}
			}
		});

		CurrentPosts_KZID.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {
				ClipboardManager cbm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
				cbm.setText(CurrentPosts_KZID.getText().toString());
				UiUtils.getInstance(INSTANCE).CreateShowToast(
						R.string.CrawlActivity_Copyed, Toast.LENGTH_SHORT);
				return false;
			}
		});

		CrawlMandate = (EditText) findViewById(R.id.CrawlMandate);
		TextWatcher textWatcher = new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				Log.d("TAG", "afterTextChanged--------------->");
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				Log.d("TAG", "beforeTextChanged--------------->");
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Log.d("TAG", "onTextChanged--------------->");
				initCurrentPostsViewData(s.toString());
				updateUI(SwitchUpdateUiCommand.UpdateCurrentPostsViewData);
			}
		};
		CrawlMandate.addTextChangedListener(textWatcher);
		CrawlMandate.setFocusable(true);
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				InputMethodManager inputManager = (InputMethodManager) CrawlMandate
						.getContext().getSystemService(
								Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(CrawlMandate, 0);
			}
		}, 998);
		DoAdditionalCrawlBtn = (Button) findViewById(R.id.DoAdditionalCrawlBtn);
		DoAdditionalCrawlBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				ToTiebaQueryParameterData = new ToTiebaQueryParameter();
				ToTiebaQueryParameterData.kzid = CrawlMandate.getText()
						.toString();
				ToTiebaQueryParameterData.postsCount = postsCount;
				ToTiebaQueryParameterData.isAdditional = true;
				startCrawlEngine(ToTiebaQueryParameterData);
			}
		});
		DoNormalCrawlBtn = (Button) findViewById(R.id.DoNormalCrawlBtn);
		DoNormalCrawlBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				ToTiebaQueryParameterData = new ToTiebaQueryParameter();
				ToTiebaQueryParameterData.kzid = CrawlMandate.getText()
						.toString();
				ToTiebaQueryParameterData.postsCount = postsCount;
				ToTiebaQueryParameterData.isAdditional = false;
				startCrawlEngine(ToTiebaQueryParameterData);
			}
		});
	}

	private void updateUI(SwitchUpdateUiCommand command) {
		switch (command) {
		case INIT:
			fillCurrentPostsViewData();
			CrawlMandate.setText(currentKzid);
			CrawlMandate.selectAll();
			CrawlMandate.setFocusable(true);
			break;
		case UpdateCurrentPostsViewData:
			fillCurrentPostsViewData();
			break;
		default:
			break;
		}
	}

	private void fillCurrentPostsViewData() {
		if (currentPosts_id == 0 || currentKzid.equals("")) {
			CurrentPostsView.setVisibility(View.GONE);
			return;
		} else {
			CurrentPostsView.setVisibility(View.VISIBLE);
		}
		String author = currentXtiebaPostsDb.author;
		XtiebaAuthor o = XtiebaAuthorDb.getNetInstance(INSTANCE).selectByName(
				author);
		String local_avatar = "";
		if (o != null && !o.local_avatar.equals("")) {
			local_avatar = o.local_avatar;
		}
		Bitmap bmp = IOUtils.makeAuthorAvatar(INSTANCE, local_avatar);
		if (bmp != null) {
			CurrentPosts_Thumbnail.setImageBitmap(bmp);
		}
		CurrentPosts_Author.setText(author);
		CurrentPosts_Title.setText(currentXtiebaPostsDb.title);
		// kzid
		CurrentPosts_KZID.setText(currentXtiebaPostsDb.kzid);
		CurrentPosts_Total.setText(postsCount + "");

		// 时间
		CurrentPosts_Date.setText(String.format(
				getString(R.string.PostsCursorAdapter_Publish), DateUtils
						.formatDateForUnixTimestamp(INSTANCE,
								currentXtiebaPostsDb.posts_created_at)));
		CurrentPosts_UpdateDate.setText(String.format(
				getString(R.string.PostsCursorAdapter_CrawlUpdate), DateUtils
						.formatDateForUnixTimestamp(INSTANCE,
								currentXtiebaPostsDb.updated_at)));
	}

	/**
	 * @param data
	 */
	private Boolean checkQueryParameter(ToTiebaQueryParameter data) {
		Boolean r = true;
		if (data.kzid.equals("")) {
			r = false;
		}
		return r;
	}

	// public static Header[] setHeader() {
	// Header[] result = {
	// new
	// BasicHeader("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"),
	// new BasicHeader("Accept-Encoding","gzip, deflate"),
	// new BasicHeader("Accept-Language","zh-CN"),
	// new BasicHeader("Cache-Control","no-cache"),
	// new BasicHeader("Connection","Keep-Alive"),
	// new BasicHeader("Content-Type","application/x-www-form-urlencoded"),
	// new BasicHeader("Host","ssl.mail.163.com"),
	// new BasicHeader("Referer","http://mail.163.com/"),
	// new BasicHeader("Accept","text/html, application/xhtml+xml, */*")
	//
	// };
	// return result;
	// }
	public static Header[] setQueryHeader(String sessionId) {
		Header[] result = {
				new BasicHeader("User-Agent",
						"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"),
				new BasicHeader("Accept-Encoding", "gzip, deflate"),
				new BasicHeader("Accept-Language", "zh-CN"),
				new BasicHeader("Cache-Control", "no-cache"),
				new BasicHeader("Connection", "Keep-Alive"),
				new BasicHeader("Content-Type",
						"application/x-www-form-urlencoded"),
				new BasicHeader("Host", "twebmail.mail.163.com"),
				new BasicHeader("Referer",
						"http://twebmail.mail.163.com/js4/index.jsp?sid="
								+ sessionId),
				new BasicHeader("Accept", "text/javascript")

		};
		return result;
	}

	@Override
	public void onSyncProgress(int step, int done, int total) {
		switch (step) {
		case 0:
			mProgressDialog
					.setMessage(getString(R.string.CrawlSync_Connecting));
			break;
		case 1:
			mProgressDialog
					.setMessage(getString(R.string.CrawlSync_GettingData));
			break;
		case 2:
			mProgressDialog.setMessage(String.format(
					getString(R.string.CrawlSync_ReadingData), done, total));
			break;
		case 3:
			mProgressDialog
					.setMessage(getString(R.string.CrawlSync_WrittingData));
			break;
		}
	}

	@Override
	public void onSyncEnd(Throwable result) {
		mSyncThread.compareAndSet(mSyncTask, null);
		if (result != null) {
			String msg = String.format(
					getResources().getString(
							R.string.Errors_WeaveSyncFailedMessage),
					result.getMessage());
			Log.e("MainActivity: Sync failed.", msg);

			ApplicationUtils.showErrorDialog(this,
					R.string.Errors_WeaveSyncFailedTitle, msg);
		} else {
			// Editor lastSyncDateEditor =
			// PreferenceManager.getDefaultSharedPreferences(this).edit();
			// lastSyncDateEditor.putLong(Constants.PREFERENCE_WEAVE_LAST_SYNC_DATE,
			// new Date().getTime());
			// lastSyncDateEditor.commit();
		}
		initCurrentPostsViewData(currentKzid);
		updateUI(SwitchUpdateUiCommand.UpdateCurrentPostsViewData);
		mProgressDialog.dismiss();
	}

	@Override
	public void onSyncCancelled() {
		mSyncThread.compareAndSet(mSyncTask, null);
		mProgressDialog.dismiss();

		if (mSyncTask.isFullSync()) {
			// Reset last sync date is this was a full sync.
			// Editor lastSyncDateEditor =
			// PreferenceManager.getDefaultSharedPreferences(this).edit();
			// lastSyncDateEditor.putLong(Constants.PREFERENCE_WEAVE_LAST_SYNC_DATE,
			// -1);
			// lastSyncDateEditor.commit();
		}
	}

	/**
	 * @param data
	 */
	public void startCrawlEngine(final ToTiebaQueryParameter data) {
		if (!checkQueryParameter(data)) {
			return;
		}
		if (!NetUtils.isConnectInternet(INSTANCE)) {
			UiUtils.getInstance(INSTANCE).CreateShowToast(
					R.string.Commons_NetError, Toast.LENGTH_SHORT);
			return;
		}
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(CrawlMandate.getWindowToken(), 0);
		if (!NetUtils.isWifi(INSTANCE)) {
			DialogInterface.OnClickListener onContinue = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					SyncTaskInfo info = SyncTaskInfo.createSyncTaskInfo(data,
							SyncTaskInfo.Command.C4BT);
					mSyncTask = new CrawlSyncTask(INSTANCE, INSTANCE);

					mProgressDialog = new ProgressDialog((Context) INSTANCE);
					mProgressDialog.setIndeterminate(true);
					mProgressDialog.setTitle(R.string.CrawlSync_SyncTitle);
					mProgressDialog
							.setMessage(getString(R.string.CrawlSync_Connecting));
					mProgressDialog.setCancelable(true);
					mProgressDialog.setOnCancelListener(new OnCancelListener() {

						@Override
						public void onCancel(DialogInterface dialog) {
							mSyncTask.cancel(true);
						}
					});

					mProgressDialog.show();

					boolean retVal = mSyncThread.compareAndSet(null, mSyncTask);
					if (retVal) {
						mSyncTask.execute(info);
					}
				}
			};
			ApplicationUtils.showContinueCancelDialog(INSTANCE,
					android.R.drawable.ic_menu_help,
					getString(R.string.Commons_Ask),
					getString(R.string.Commons_NoWifi), onContinue, null);
		} else {
			SyncTaskInfo info = SyncTaskInfo.createSyncTaskInfo(data,
					SyncTaskInfo.Command.C4BT);
			mSyncTask = new CrawlSyncTask(INSTANCE, INSTANCE);

			mProgressDialog = new ProgressDialog((Context) INSTANCE);
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.setTitle(R.string.CrawlSync_SyncTitle);
			mProgressDialog
					.setMessage(getString(R.string.CrawlSync_Connecting));
			mProgressDialog.setCancelable(true);
			mProgressDialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					mSyncTask.cancel(true);
				}
			});

			mProgressDialog.show();

			boolean retVal = mSyncThread.compareAndSet(null, mSyncTask);
			if (retVal) {
				mSyncTask.execute(info);
			}
		}
	}

	/**
	 * @param s
	 */
	public void initCurrentPostsViewData(String kzid) {
		currentKzid = kzid;
		currentPosts_id = 0;
		postsCount = 0;
		if (!currentKzid.equals("")) {
			currentXtiebaPostsDb = XtiebaPostsDb.getNetInstance(INSTANCE)
					.selectByKzid(currentKzid);
			if (currentXtiebaPostsDb != null) {
				currentPosts_id = currentXtiebaPostsDb.id;
				postsCount = XtiebaPostsInfoDb.getNetInstance(INSTANCE)
						.getCountByPosts_id(currentPosts_id);
			}
		} else {
			LogUtlils.println("currentKzid==空");
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
		}
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
